package com.ruoyi.quartz.task;


import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
@Slf4j
public class RyTask {
    @Autowired
    private RxOrderMapper rxOrderMapper;
    @Autowired
    private RxOrderFollowMapper of;
    @Autowired
    private OrderAllocationConfigMapper orderAllocationConfigMapper;
    @Autowired
    private SysReceiveOrderConfigMapper sysReceiveOrderConfigMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;


    private static final Long ALL_ROUND_ANCHOR_ROLE_ID = 111L;
    private volatile int XZ_INDEX = 0;

    public void ryParams(String params) {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            return;
        }
        List<RxOrder> rxOrders = rxOrderMapper.getNotAllocationOrders();
        log.info("未分配订单数量为:{},订单号:{}", rxOrders.size(), rxOrders);
        if (CollectionUtils.isEmpty(rxOrders)) {
            return;
        }
        log.info("目前需要处理抖店订单号是:{}", rxOrders.stream().map(RxOrder::getDoudianOrderId).collect(Collectors.toList()));

        Iterator<RxOrder> iterator = rxOrders.iterator();
        //其它
        OrderAllocationConfig orderAllocationConfig = orderAllocationConfigMapper.selectOrderAllocationConfigById(1L);
        List<String> rule2Contents = Arrays.stream(orderAllocationConfig.getRule2GoodsId().split(",")).distinct().collect(Collectors.toList());
        List<SysUser> openReceiveOrderUsers = sysUserMapper.getOpenReceiveOrderUsers();
        List<Long> openReceiveOrderUserIds = openReceiveOrderUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
        SysReceiveOrderConfig sysReceiveOrderConfig1 = new SysReceiveOrderConfig();
        sysReceiveOrderConfig1.setSwith(1);
        sysReceiveOrderConfig1.setType(1);
        List<Long> chengDuZong = sysReceiveOrderConfigMapper.selectSysReceiveOrderConfigList(sysReceiveOrderConfig1).stream().map(SysReceiveOrderConfig::getUserId).collect(Collectors.toList());
        List<Long> chengDuActiveUserIds = new ArrayList<>();
        for (Long userId : chengDuZong) {
            if (openReceiveOrderUserIds.contains(userId)) {
                chengDuActiveUserIds.add(userId);
            }
        }
        log.info("满足成都单的用户id是:{}", chengDuActiveUserIds);
        SysReceiveOrderConfig sysReceiveOrderConfig2 = new SysReceiveOrderConfig();
        sysReceiveOrderConfig2.setSwith(1);
        sysReceiveOrderConfig2.setType(2);
        List<Long> xieZhuanZong = sysReceiveOrderConfigMapper.selectSysReceiveOrderConfigList(sysReceiveOrderConfig2).stream().map(SysReceiveOrderConfig::getUserId).collect(Collectors.toList());
        List<Long> xieZhuanActiveUserIds = new ArrayList<>();
        for (Long userId : xieZhuanZong) {
            if (openReceiveOrderUserIds.contains(userId)) {
                xieZhuanActiveUserIds.add(userId);
            }
        }
        log.info("满足携转单的用户id是:{}", xieZhuanActiveUserIds);
        SysReceiveOrderConfig sysReceiveOrderConfig3 = new SysReceiveOrderConfig();
        sysReceiveOrderConfig3.setSwith(1);
        sysReceiveOrderConfig3.setType(3);
        List<Long> zaiTuZong = sysReceiveOrderConfigMapper.selectSysReceiveOrderConfigList(sysReceiveOrderConfig3).stream().map(SysReceiveOrderConfig::getUserId).collect(Collectors.toList());
        List<Long> zaiTuActiveUserIds = new ArrayList<>();
        for (Long userId : zaiTuZong) {
            if (openReceiveOrderUserIds.contains(userId)) {
                zaiTuActiveUserIds.add(userId);
            }
        }
        log.info("满足在途接单的用户id是:{}", zaiTuActiveUserIds);

        while (iterator.hasNext()) {
            RxOrder order = iterator.next();
            log.info("目前需要处理抖店订单号是:{},订单id:{}", order.getDoudianOrderId(), order.getId());
            Long doudianOrderManageAuthorId = order.getDoudianOrderManageAuthorId();
            if (doudianOrderManageAuthorId != null) {
                log.info("全能主播userId:{},订单号是:{}", doudianOrderManageAuthorId, order.getId());
                List<SysUserRole> sysUserRoles = userRoleMapper.selectRolesByUserId(doudianOrderManageAuthorId);
                if (sysUserRoles.size() > 0) {
                    List<Long> roles = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
                    log.info("全能主播角色有:{}", roles);
                    if (roles.contains(ALL_ROUND_ANCHOR_ROLE_ID)) {
                        log.info("全能主播,订单分给他userId:{},订单号是:{}", doudianOrderManageAuthorId, order.getId());
                        rxOrderMapper.updateReceiveOrderUserIdById(order.getDoudianOrderManageAuthorId(), order.getId());
                        iterator.remove();
                        RxOrderFollow rof = new RxOrderFollow();
                        rof.setTime(System.currentTimeMillis() / 1000);
                        rof.setOrderId(order.getId().intValue());
                        rof.setManageId(Math.toIntExact(doudianOrderManageAuthorId));
                        rof.setTitle("【自动分配订单】");
                        rof.setContent("该订单已触发【优先级最高）全能主播订单】分配策略,已将订单分配给跟全能主播" + sysUserMapper.selectUserById(doudianOrderManageAuthorId).getNickName());
                        of.insertRxOrderFollow(rof);
                        continue;
                    }
                }
            }

            if (null != zaiTuZong && (
                    "3759479174591545549".equals(order.getDoudianOrderProductId()) ||
                            "3754894490461143521".equals(order.getDoudianOrderProductId()) ||
                            "3754895224707613621".equals(order.getDoudianOrderProductId()) ||
                            "3754895639272620508".equals(order.getDoudianOrderProductId()) ||
                            "3712181777171874079".equals(order.getDoudianOrderProductId()) ||
                            "3758618087461617678".equals(order.getDoudianOrderProductId()) ||
                            "3758618261298741755".equals(order.getDoudianOrderProductId()) ||
                            "3758618385961845293".equals(order.getDoudianOrderProductId()) ||
                            "3739133422728249754".equals(order.getDoudianOrderProductId()) ||
                            "3761737603712417839".equals(order.getDoudianOrderProductId()) ||
                            "3763969474903015906".equals(order.getDoudianOrderProductId())

            )

            ) {
                HashMap<Long, Integer> chengDu_receiveOrderCountByUserId = new HashMap<>();
                chengDu_receiveOrderCountByUserId.clear();
                HashMap<Long, Integer> chengDu_lowAverage = new HashMap<>();
                chengDu_lowAverage.clear();
                int chengDu_hasOrderCountByAllUser = 0;
                for (Long userId : chengDuActiveUserIds) {
                    int currentUserCount = rxOrderMapper.getHasReceiveOrderByUserId(userId);
                    chengDu_receiveOrderCountByUserId.put(userId, currentUserCount);
                    chengDu_hasOrderCountByAllUser = chengDu_hasOrderCountByAllUser + currentUserCount;
                }
                int chengDu_average = (rxOrders.size() + chengDu_hasOrderCountByAllUser) / chengDuActiveUserIds.size();
                log.info("成都订单未分配订单数是:{},已分配订单数:{},接单总人数是:{},平均值是:{}", rxOrders.size(), chengDu_hasOrderCountByAllUser, chengDuActiveUserIds.size(), chengDu_average);
                for (Map.Entry<Long, Integer> m : chengDu_receiveOrderCountByUserId.entrySet()) {
                    log.info("成都接单人Id:{}--当前手上有:{}单", m.getKey(), m.getValue());
                    if (0 > (m.getValue() - chengDu_average)) {
                        chengDu_lowAverage.put(m.getKey(), m.getValue());
                    }
                }
                log.info("成都小于平均值的用户是:{}", chengDu_lowAverage);
                if (0 == chengDu_lowAverage.size() && rxOrders.size() > 0 && chengDuActiveUserIds.size() > 0) {
                    Long userId = chengDuActiveUserIds.get(0);
                    log.info("成都用户各用户的订单数量都一样,现取第一个用户将订单分给他userId:{},订单号是:{}", userId, order.getId());
                    rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级1）成都所有订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                }
                if (chengDu_lowAverage.size() > 0) {
                    Map.Entry<Long, Integer> minEntry = chengDu_lowAverage.entrySet()
                            .stream()
                            .min(Map.Entry.comparingByValue())
                            .orElse(null);
                    if (minEntry != null) {
                        log.info("成都最小value的记录: 用户id是={},当前单数是={}", minEntry.getKey(), minEntry.getValue());
                        rxOrderMapper.updateReceiveOrderUserIdById(minEntry.getKey(), order.getId());
                        RxOrderFollow rof = new RxOrderFollow();
                        rof.setTime(System.currentTimeMillis() / 1000);
                        rof.setOrderId(order.getId().intValue());
                        rof.setManageId(52);
                        rof.setTitle("【自动分配订单】");
                        rof.setContent("该订单已触发【优先级1）成都所有订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(minEntry.getKey()).getNickName());
                        of.insertRxOrderFollow(rof);
                        iterator.remove();
                        continue;
                    }
                }
            }
            log.info("成都分完订单还剩:{}单", rxOrders.size());
            if (rxOrders.size() == 0) {
                break;
            }
            if (rxOrders.size() > 0 && order.getDoudianOrderSpec().contains(orderAllocationConfig.getRule1MatchText()) && null != xieZhuanZong) {
                log.info("进去携转,订单区域是:{}", order.getAreaId());
                if (rxOrders.size() > 0 && StringUtils.isNotEmpty(order.getAreaId()) && order.getAreaId().contains("渝中") && xieZhuanActiveUserIds.contains(70L)) {
                    log.info("进去携转,订单区域包含渝中走70L,抖店id:{}", order.getDoudianOrderId());
                    rxOrderMapper.updateReceiveOrderUserIdById(70L, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(70L).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                } else if (rxOrders.size() > 0 && StringUtils.isNotEmpty(order.getAreaId()) && order.getAreaId().contains("巴南") && xieZhuanActiveUserIds.contains(80L)) {
                    log.info("进去携转,订单区域包含巴南走80L,抖店id:{}", order.getDoudianOrderId());
                    rxOrderMapper.updateReceiveOrderUserIdById(80L, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(80L).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                } else if (rxOrders.size() > 0 && StringUtils.isNotEmpty(order.getAreaId()) && order.getAreaId().contains("大渡口") && xieZhuanActiveUserIds.contains(61L)) {
                    log.info("进去携转,订单区域包含大渡口走61L,抖店id:{}", order.getDoudianOrderId());
                    rxOrderMapper.updateReceiveOrderUserIdById(61L, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(61L).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                } else if (rxOrders.size() > 0 && StringUtils.isNotEmpty(order.getAreaId()) && (order.getAreaId().contains("九龙坡") || order.getAreaId().contains("沙坪坝"))
                        && xieZhuanActiveUserIds.contains(211L)) {
                    log.info("进去携转,订单区域包含九龙坡,沙坪坝胡萍,抖店id:{}", order.getDoudianOrderId());
                    rxOrderMapper.updateReceiveOrderUserIdById(211L, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(211L).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                }
                if (rxOrders.size() == 0) {
                    break;
                }

                log.info(" xieZhuanActiveUserIds:{},size:{}", xieZhuanActiveUserIds, xieZhuanActiveUserIds.size());
                if (xieZhuanActiveUserIds.size() > 0 && XZ_INDEX == 0) {
                    XZ_INDEX = XZ_INDEX + 1;
                    Long userId = xieZhuanActiveUserIds.get(0);
                    log.info("进去携转,抖店id:{},用户id:{},下标:{}", order.getDoudianOrderId(), userId, XZ_INDEX);
                    rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    if (1 == xieZhuanActiveUserIds.size()) {
                        XZ_INDEX = 0;

                    }
                    continue;
                } else if (xieZhuanActiveUserIds.size() > 0 && XZ_INDEX == 1) {
                    XZ_INDEX = XZ_INDEX + 1;
                    Long userId = null;
                    if (xieZhuanActiveUserIds.size() == 1) {
                        userId = xieZhuanActiveUserIds.get(0);

                    }
                    if (xieZhuanActiveUserIds.size() == 2) {
                        userId = xieZhuanActiveUserIds.get(1);

                    }
                    if (xieZhuanActiveUserIds.size() == 3) {
                        userId = xieZhuanActiveUserIds.get(1);
                    }
                    if (xieZhuanActiveUserIds.size() == 4) {
                        userId = xieZhuanActiveUserIds.get(1);
                    }
                    log.info("进去携转,抖店id:{},用户id:{},下标:{}", order.getDoudianOrderId(), userId, XZ_INDEX);
                    rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    if (2 == xieZhuanActiveUserIds.size()) {
                        XZ_INDEX = 0;
                    }
                    continue;
                } else if (xieZhuanActiveUserIds.size() > 0 && XZ_INDEX == 2) {
                    XZ_INDEX = XZ_INDEX + 1;
                    Long userId = null;
                    if (xieZhuanActiveUserIds.size() == 1) {
                        userId = xieZhuanActiveUserIds.get(0);
                    }
                    if (xieZhuanActiveUserIds.size() == 2) {
                        userId = xieZhuanActiveUserIds.get(1);
                    }
                    if (xieZhuanActiveUserIds.size() == 3) {
                        userId = xieZhuanActiveUserIds.get(2);
                    }
                    if (xieZhuanActiveUserIds.size() == 4) {
                        userId = xieZhuanActiveUserIds.get(2);
                    }
                    log.info("进去携转,抖店id:{},用户id:{},下标:{}", order.getDoudianOrderId(), userId, XZ_INDEX);
                    rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    if (3 >= xieZhuanActiveUserIds.size()) {
                        XZ_INDEX = 0;
                    }
                    continue;
                } else if (xieZhuanActiveUserIds.size() > 0 && XZ_INDEX == 3) {
                    XZ_INDEX = XZ_INDEX + 1;
                    Long userId = null;
                    if (xieZhuanActiveUserIds.size() == 1) {
                        userId = xieZhuanActiveUserIds.get(0);
                    }
                    if (xieZhuanActiveUserIds.size() == 2) {
                        userId = xieZhuanActiveUserIds.get(1);
                    }
                    if (xieZhuanActiveUserIds.size() == 3) {
                        userId = xieZhuanActiveUserIds.get(2);
                    }
                    if (xieZhuanActiveUserIds.size() == 4) {
                        userId = xieZhuanActiveUserIds.get(3);
                    }
                    log.info("进去携转,抖店id:{},用户id:{},下标:{}", order.getDoudianOrderId(), userId, XZ_INDEX);
                    rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级2）重庆携转订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    if (4 >= xieZhuanActiveUserIds.size()) {
                        XZ_INDEX = 0;
                    }
                    continue;
                }
            }

            if (rxOrders.size() == 0) {
                break;
            }
            HashMap<Long, Integer> receiveOrderCountByUserId = new HashMap<>();
            receiveOrderCountByUserId.clear();
            HashMap<Long, Integer> lowAverage = new HashMap<>();
            lowAverage.clear();
            int hasOrderCountByAllUser = 0;
            for (Long userId : zaiTuActiveUserIds) {
                int currentUserCount = rxOrderMapper.getHasReceiveOrderByUserId(userId);
                receiveOrderCountByUserId.put(userId, currentUserCount);
                hasOrderCountByAllUser = hasOrderCountByAllUser + currentUserCount;
            }

            int average = (rxOrders.size() + hasOrderCountByAllUser) / zaiTuActiveUserIds.size();
            log.info("重庆在途订单未分配订单数是:{},已分配订单数:{},接单总人数是:{},平均值是:{}", rxOrders.size(), hasOrderCountByAllUser, zaiTuActiveUserIds.size(), average);
            for (Map.Entry<Long, Integer> m : receiveOrderCountByUserId.entrySet()) {
                if (0 > m.getValue() - average) {
                    lowAverage.put(m.getKey(), m.getValue());
                }
            }

            if (0 == lowAverage.size() && rxOrders.size() > 0 && zaiTuActiveUserIds.size() > 0) {
                Long userId = zaiTuActiveUserIds.get(0);
                log.info("重庆在途用户各用户的订单数量都一样,现取第一个用户将订单分给他userId:{},订单号是:{}", userId, order.getId());
                rxOrderMapper.updateReceiveOrderUserIdById(userId, order.getId());
                RxOrderFollow rof = new RxOrderFollow();
                rof.setTime(System.currentTimeMillis() / 1000);
                rof.setOrderId(order.getId().intValue());
                rof.setManageId(52);
                rof.setTitle("【自动分配订单】");
                rof.setContent("该订单已触发【优先级3）重庆正常订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(userId).getNickName());
                of.insertRxOrderFollow(rof);
                iterator.remove();
                continue;
            }
            if (lowAverage.size() > 0) {
                Map.Entry<Long, Integer> minEntry = lowAverage.entrySet()
                        .stream()
                        .min(Map.Entry.comparingByValue())
                        .orElse(null);
                if (minEntry != null) {
                    log.info("重庆最小value的记录: 用户id是={},当前单数是={}", minEntry.getKey(), minEntry.getValue());
                    rxOrderMapper.updateReceiveOrderUserIdById(minEntry.getKey(), order.getId());
                    RxOrderFollow rof = new RxOrderFollow();
                    rof.setTime(System.currentTimeMillis() / 1000);
                    rof.setOrderId(order.getId().intValue());
                    rof.setManageId(52);
                    rof.setTitle("【自动分配订单】");
                    rof.setContent("该订单已触发【优先级3）重庆正常订单】分配策略,已将订单分配给跟单客服" + sysUserMapper.selectUserById(minEntry.getKey()).getNickName());
                    of.insertRxOrderFollow(rof);
                    iterator.remove();
                    continue;
                }
            }
        }
        log.info("分单结束!");
    }

    public void refreshDouDianToken() {
    }

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

}
